import { useHistory } from 'react-router-dom';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import StationForm from './components/StationForm';
import RegionTree from '@/components/biz/RegionTree';

const Station = () => {
  return (
    <TauPage className="page-container-2">
      <CityList />
      <StationList />
    </TauPage>

  );
};

const CityList = observer(() => {
  const { ccStationStore: store } = useStore();

  useEffect(() => {
    store.region = {};
    (async () => {
      await store.getHotRegion();
    })();
  }, []);

  return (
    <div className="left-panel" style={{ maxWidth: 220, minWidth: 220, padding: 10, borderRight: 'solid 1px var(--color-fill1-4)' }}>
      <RegionTree
        onRegion={(r) => { store.region = r; }}
      />
    </div>
  );
});

const StationList = observer(() => {
  const { ccStationStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const objRef = useRef();
  const history = useHistory();

  useEffect(() => {
    (async () => {
      await store.allRegions(2);
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    // console.log('params:', params);
    const { stationType, hot, ...search } = params.values;
    if (stationType !== undefined) {
      _.merge(search, { extras: { 'transfer.value': stationType === '1' } });
    }
    if (hot) {
      const keywordsRegex = new RegExp(hot.map((keyword) => `(${keyword})`).join('|'), 'u');
      _.merge(search, { extras: { 'hot.value': keywordsRegex } });
    }
    store.search = search;
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    objRef.current = { parentId: store.region.itemId };
    setModal(['add']);
  };

  // 点击打开查看
  const handleOpenView = (station) => {
    objRef.current = station;
    setModal(['view']);
  };

  // 点击打开编辑
  const handleOpenEdit = (station) => {
    objRef.current = station;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // eslint-disable-next-line no-param-reassign
        await store.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleRemove = (station) => {
    Dialog.confirm({
      content: t`删除【${station.name}】吗？`,
      onOk: () => store.remove(station),
    });
  };


  return (
    <div className="main-content" >
      <TauActionPanel
        className="action-panel"
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-group',
            title: t`区域分组`,
            type: 'primary',
            onClick: () => { history.push('/price/cc-station/group'); },
          },
          {
            name: 'btn-placeStation',
            title: t`添加站点`,
            type: 'primary',
            disabled: !store.isDictrict(),
            onClick: handleOpenAdd,
          },
        ]}
        searchItems={[
          {
            name: 'stationType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.stationType),
              placeholder: t`站点类型`,
            },
          },
          {
            name: 'hot',
            type: 'select',
            props: {
              dataSource: store.hotRegion,
              placeholder: t`热门区域`,
              mode: 'multiple',
              style: { minWidth: 200 },
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
      />
      <div className="content">
        <TauTable
          primaryKey="itemId"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.stations)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('itemId', { width: 88, cell: (v, _, station) => <Button type="primary" text onClick={() => handleOpenView(station)}>{v}</Button> }),
            column('city', {}),
            column('district', {}),
            column('name', {}),
            column('disabled', { width: 100 }),
            // column('sortWeight', { width: 88 }),
            {
              title: t`站点类型`,
              dataIndex: 'stationType',
              cell: (v, i, row) => {
                const stationType = row.extras?.transfer?.value ? 1 : 0;
                return ENUMS.stationType[stationType];
              },
            },
            column('ts', { width: 124, sortable: true }),
            {
              title: t`操作`,
              dataIndex: 'stationNumber',
              width: 100,
              cell: (_, __, station) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(station)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" onClick={() => handleRemove(station)} >{t`删除`}</Button>
                </>),
            },
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'add' ? t`添加区域` : t`修改区域【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="700px"
      >
        <StationForm
          stationId={objRef.current?.itemId}
          parentId={objRef.current?.parentId}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
    </div>
  );
});

export default Station;
